package com.itbaizhan.ruiji.controller;

import com.itbaizhan.ruiji.common.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

//文件上传与下载
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    @Value("${ruiji.path}")
    private String basePath;
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        File dir = new File(basePath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        String originalfilename=file.getOriginalFilename();
        String suffix = originalfilename.substring(originalfilename.lastIndexOf("."));
        String filname = UUID.randomUUID().toString()+suffix;
        file.transferTo(new File(basePath+filname));
        return Result.success(filname);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            int len=0;
            byte[] bytes = new byte[1024];
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));
            response.setContentType("image/jpeg");
            ServletOutputStream outputStream = response.getOutputStream();
            while((len=fileInputStream.read(bytes)) !=-1){
                    outputStream.write(bytes,0,len);
                    outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
        }
    }
}
